<template>
    <div class="financialPro">
        <Card class="mb10">
            <Form ref="financialProdForm" :model="financialProdForm" :rules="financialProdFormValiate"
                  :label-width="90">
                <div class="common_br" style="border: none;background-color: white;">
                    <div class="common_content">
                        <Row>
                            <Col span="10" style="padding-left:24px;">
                                <FormItem label="产品名称" prop="id" class="prodName">
                                    <Select v-model="financialProdForm.id"
                                            :placeholder="mainProductName"
                                            @on-change="selectPord"
                                            :label-in-value="true"
                                            @on-open-change="queryProductSelectList($event)"
                                            :disabled="isShowDetails||isDisabled"
                                    >
                                        <Option :value="item.id" style="width: 550px"
                                                v-for="(item,index) in prodNameList" :key="index">{{item.productName}}
                                        </Option>
                                        <Page
                                            v-show="prodNameList.length>0"
                                            :page-size="pageData.pageSize"
                                            :total="pageData.total"
                                            @on-change="changePage"
                                            style="text-align: center;"
                                            simple/>
                                    </Select>
                                </FormItem>
                            </Col>
                        </Row>
                    </div>
                </div>
            </Form>
            <div style="background:white">
                <Row>
                    <total-info
                        :totalInfoData="totalInfoData"
                        :isAdditional="isAdditional"
                        :isSubProduct="isSubProduct"
                        ref="totalInfo"
                        :uuid="uuid"
                        :isAppear="isAppear"
                        @isChange="isChange"
                        @isDeal="isDeal"
                        :isDisabled="isDisabled"
                        :loanAmtMax="loanAmtMax"
                    ></total-info>
                </Row>
                <Row>
                    <car-loan
                        :queryCarProductInfo="queryCarProductInfo"
                        :selectCarProductInfo="selectCarProductInfo"
                        :isCarTail="isCarTail"
                        :carMonthPay="carMonthPay"
                        :carDiscount="carDiscount"
                        :carTotalInterest="carTotalInterest"
                        ref="carloan"
                        :uuid="uuid"
                        :isAppear="isAppear"
                        :carPrice="carPrice"
                        :isShowDetails="isShowDetails"
                        :mainProductId="mainProductId"
                        :applyNo="applyNo"
                        @isChange="isChange"
                        v-if="isAdditional=='0'||(isAdditional=='1'&&isSubProduct=='1')"
                        :isDisabled="isDisabled"
                        :carDiscountOption="carDiscountOption"
                        :isAdditional="isAdditional"
                        :isSubProduct="isSubProduct"
                    >
                    </car-loan>
                    <carAdditional-loan
                        v-if="isAdditional=='1'&&isSubProduct=='0'"
                        :isCarTail="isCarTail"
                        :isShowDetails="isShowDetails"
                        :carMonthPay="carMonthPay"
                        :carDiscount="carDiscount"
                        :carTotalInterest="carTotalInterest"
                        :uuid="uuid"
                        :isAppear="isAppear"
                        :carPrice="carPrice"
                        :isAdditional="isAdditional"
                        :isSubProduct="isSubProduct"
                        :selectProductInfo="selectProductInfo"
                        :queryCarProductInfo="queryCarProductInfo"
                        ref="carAddLoan"
                        @isChange="isChange"
                        :mainProductId="mainProductId"
                        :applyNo="applyNo"
                        :carDiscountOption="carDiscountOption"
                        :isDisabled="isDisabled"
                    ></carAdditional-loan>
                </Row>
                <Row>
                    <div v-if="isAdditional=='1'&&isSubProduct=='1'">
                        <additional-loan
                            :selectProductInfo="selectProductInfo"
                            :selectCarProductInfo="selectCarProductInfo"
                            :queryProductInfo="queryProductInfo"
                            :addMonthPay="addMonthPay"
                            :addDiscount="addDiscount"
                            :addTotalInterest="addTotalInterest"
                            :uuid="uuid"
                            :isAppear="isAppear"
                            @isChange="isChange"
                            :isShowDetails="isShowDetails"
                            :isAdditional="isAdditional"
                            :isSubProduct="isSubProduct"
                            :addProductId="addProductId"
                            :mainProductId="mainProductId"
                            :applyNo="applyNo"
                            :isAdditionalTail="isAdditionalTail"
                            :isDisabled="isDisabled"
                            :additionalDiscountOption="additionalDiscountOption"
                            ref="additionalLoan"></additional-loan>
                    </div>
                </Row>
            </div>
            <!-- </Card> -->
            <slot name="afsBusiness"></slot>
        </Card>
    </div>
</template>
<script>
    import CarLoan from "./car-loan/carLoan";
    import AdditionalLoan from "./additional-loan/additionalLoan"
    import CarAdditionalLoan from "./carAdditional-loan/carAdditionalLoan"
    import TotalInfo from "./total-info/totalInfo"
    import {
        getCostList,
        getProductSelectList,
        queryProductDetails,
        saveCostList,
        updateCostList,
        financeCalculation,
        initProductParam,
        getArbitraryRepaymentPlan
    } from "_p/afs-apply/api/apply-report/personal/financialProducts.js"
    import {prodRes, prodRes1, initData, resPlan, selectList} from "@/projects/afs-apply/assets/js/staticData.js"
    import {deepClone} from "@/libs/utils/ObjectClone";
    import * as utils from '_p/afs-apply/assets/js/utils.js'
    import "../../../../../afs-apply/assets/css/base.css";
    //融资信息重置 add by  gjq
    import {resetCostInfo} from "@/projects/afs-core-business/pages/case/approve/defines/financialReset"

    export default {
        name: "financialProducts",
        data() {
            return {
                isDisabled: true,
                tempRepaymentList: [],
                modifyRepayList: [],
                // isSaveDisabled:true,
                carPrice: "",
                isAdditional: "0",//附加贷
                isSubProduct: "0",//0没有子产品,是主产品跟子产品相同,1有子产品,是主产品跟子产品不相同
                carDiscountOption: "0",//车贷贴息方式
                additionalDiscountOption: "0",//附加贷贴息方式
                isCarTail: "", //车贷是否有尾款
                isAdditionalTail: "",//附加贷是否有尾款
                mainProductId: "",
                mainProductName: "",
                addProductId: "",
                addProductName: "",
                addAlgorithmType: "",
                carAlgorithmType: "",
                carMonthPay: 0,
                addMonthPay: 0,
                addFinancialId: "",
                carFinancialId: "",
                // 计算接口返回保存增加
                // 租金
                carTotalRent: "",
                addTotalRent: "",
                // 利息
                carTotalInterest:0,
                addTotalInterest:0,
                // 贴息金额
                addDiscount:0,
                carDiscount:0,

                pageData: {
                    pageNumber: 1,
                    pageSize: 10,
                    total: 0
                },
                addRepaymentData: {},
                carRepaymentData: {},

                financialProdForm: {
                    id: "",
                },
                financialProdFormValiate: {
                    // id:[
                    //     {required: true, message: "产品名称不能为空", trigger: "change"}
                    // ]
                },
                // prodNameList:[],
                prodNameList: [],
                // 选择产品的附加贷产品的变量
                selectProductInfo: {},
                // 选择产品的产品详细信息的变量
                selectCarProductInfo: {},

                // 修改回显的附加贷产品的变量
                queryProductInfo: {},
                // 修改回显的车贷的信息
                queryCarProductInfo: {},
                // 修改回显合计信息
                totalInfoData: {
                    totalInterest: "",
                    totalDiscountAmt: "",
                    totalRent: "",
                    totalTailAmt: "",
                },
                // 选择产品的入参
                selectParam: {},
                //留痕
                carLoanFormOldData: {
                    downPayScale: "",
                    downPayAmt: "",
                    tailPayScale: "",
                    tailPayAmt: "",
                    loanAmt: "",
                    custRate: "",
                    monthPayAmt: "",
                    totalInterest: "",
                    maxDisCountAmt: "",
                    discountType: "",
                    discountTotalAmt: "",
                },
                flag:false
            }
        },
        components: {
            CarLoan,
            AdditionalLoan,
            TotalInfo,
            CarAdditionalLoan
        },
        props: {
            //理论最大额度
            loanAmtMax: {
                type: Number
            },
            applyNo: {
                type: String,
            },
            curTab: {
                type: String
            },
            isShowDetails: {
                type: Boolean,
            },
            uuid: {
                type: String,
            },
            isAppear: {
                type: Boolean
            },
            intropath: {
                type: String,
            },
            proessFormValidate: {
                type: String,
            },
            proessForm: {
                type: Object,
            },
            additionalProessForm: {
                type: Object,
            },
            carProessForm: {
                type: Object,
            },
            queryFormEl: {
                type: Function,
            }
        },
        watch: {
            curTab(val) {
                if (val == "name2") {
                    if(this.flag){
                      return ;
                    }
                    this.flag=true;
                    if (this.applyNo) {
                        this.modfiyInitCostList(this.applyNo);
                        /* this.queryProductParam(this.applyNo);*/
                    }
                }
            },

        },
        // inject: ['curTab'],
        mounted() {
        },
        methods: {
            isChange(val) {
                this.$emit('isChange', val);
            },
            isDeal() {
                if (this.isAdditional=='1' && this.isSubProduct=='0') {
                    this.$refs.carAddLoan.isDeal();
                }
                if (this.isAdditional=='0'||(this.isAdditional=='1' && this.isSubProduct=='1')) {
                    this.$refs.carloan.isDeal();
                }
                if (this.isAdditional=='1' && this.isSubProduct=='1') {
                    this.$refs.additionalLoan.isDeal();
                }
            },
            // add by gjq 融资信息重置
            resetFinancialInfo() {
                let param = {
                    applyNo: this.applyNo
                }
                resetCostInfo(param).then(res => {
                    if (res.code == "0000") {
                        this.$Message.success("重置成功");
                    }
                    this.modfiyInitCostList(this.applyNo);
                })

            },

            queryProductParam(applyNo) {
                let params = {
                    applyNo: applyNo,
                }
                initProductParam(params, "case").then(res => {
                    if (res.code == "0000") {
                        this.selectParam.applyNo = applyNo;
                        if (res.data) {
                            this.carPrice = res.data.salePrice.toString();
                        }
                    }
                })
            },
            // 下拉框展开获取产品list
            queryProductSelectList(val) {
                if (val) {
                    this.selectParam.applyNo = this.applyNo;
                    this.selectParam.pageSize = this.pageData.pageSize;
                    this.selectParam.pageNo = this.pageData.pageNumber;
                    getProductSelectList(this.selectParam, "case").then(res => {
                        if (res.code == "0000") {
                            if (res.data) {
                                this.prodNameList = res.data.records;
                                this.pageData.total = res.data.total;
                            }
                        }
                    })
                }
            },
            changePage(value) {
                this.pageData.pageNumber = value;
                this.queryProductSelectList(this.selectParam);
            },
            // 修改初始化查询贷款信息
            modfiyInitCostList(applyNo) {
                let param = {
                    applyNo: applyNo,
                    carId: "",
                }
                getCostList(param, "case").then(res => {
                    if (res.code == "0000") {
                        if (res.data.salePrice) {
                            this.carPrice = res.data.salePrice.toString();
                        }
                        if (Object.keys(res.data).length > 1) {
                            // 回显的时候产品的附加贷跟贴息方式
                            this.isAdditional = res.data.isAdditional;
                            this.isSubProduct = res.data.isSubProduct;
                            if (res.data.rentList && res.data.rentList.length > 0) {
                                this.modifyRepayList = deepClone(res.data.rentList);
                            }
                            let _this = this;
                            this.$nextTick(() => {
                                if (res.data.carProductInfo) {
                                    if (res.data.carProductInfo.costInfoOld) {
                                        // 留痕
                                        this.carLoanFormOldData = res.data.carProductInfo.costInfoOld;
                                    } else {
                                        // 留痕
                                        this.carLoanFormOldData = res.data.carProductInfo.costInfo;
                                    }
                                    _this.mainProductId = res.data.carProductInfo.costInfo.productId;
                                    _this.financialProdForm.id = res.data.carProductInfo.costInfo.productId;
                                    _this.mainProductName = res.data.carProductInfo.costInfo.productName;
                                    // 修改赋值产品那条数据的id
                                    _this.carFinancialId = res.data.carProductInfo.costInfo.id;
                                }
                                if (_this.isAdditional == "1") {
                                    if (res.data.addProductInfo) {
                                        _this.addFinancialId = res.data.addProductInfo.costInfo.id;
                                    }
                                }
                                // 保证回显的值，覆盖产品详情值
                                if (res.data.carProductInfo) {
                                    _this.initProductDetails(res.data.carProductInfo.costInfo.productId).then((val) => {
                                        if (val.addProductInfo) {
                                            if (res.data.addProductInfo) {
                                                _this.queryProductInfo = deepClone(res.data.addProductInfo);
                                            }
                                        }
                                        if (val.mainProductInfo) {
                                            _this.queryCarProductInfo = deepClone(res.data.carProductInfo);

                                        }
                                    })
                                }
                                // 合计金额
                                let tempTotalAmt = {
                                    totalcontAmt: res.data.totalContractAmt,
                                    totalLoanAmt: res.data.totalLoanAmt,
                                    totalFirstAmt: res.data.totalFirstAmt,
                                    totalDiscountAmt: res.data.totalDiscountAmt,
                                    totalInterest: res.data.totalInterest,
                                    totalRent: ((res.data.addProductInfo != null) ?
                                        utils.add(res.data.carProductInfo.costInfo.monthPayAmt,res.data.addProductInfo.costInfo.monthPayAmt) : (res.data.carProductInfo.costInfo.monthPayAmt)),
                                    totalTailAmt: res.data.totalTailAmt,
                                    //留痕
                                    totalcontAmtOld: res.data.totalContractAmtOld,
                                    totalLoanAmtOld: res.data.totalLoanAmtOld,
                                    totalFirstAmtOld: res.data.totalFirstAmtOld,
                                    totalDiscountAmtOld: res.data.totalDiscountAmtOld,
                                    totalInterestOld: res.data.totalInterestOld,
                                    totalTailAmtOld: res.data.totalTailAmtOld
                                }

                                let totalRentOld="";
                                if(res.data.addProductInfo!=null){
                                    if(res.data.carProductInfo.costInfoOld){
                                        let carmonthPayAmt=res.data.carProductInfo.costInfoOld.monthPayAmt;
                                        totalRentOld=carmonthPayAmt;
                                        if(res.data.addProductInfo.costInfoOld){
                                            totalRentOld=utils.add(totalRentOld,res.data.addProductInfo.costInfoOld.monthPayAmt||'')
                                        }

                                    }
                                }else{
                                    totalRentOld=res.data.carProductInfo.costInfoOld.monthPayAmt;
                                }
                                tempTotalAmt.totalRentOld=totalRentOld;
                                _this.totalInfoData = tempTotalAmt;
                            })
                        }
                    }
                })
            },
            // 选择产品
            selectPord(val) {
                if (val) {
                    this.mainProductId = val.value;
                    if (this.intropath == "afsProduct") {
                        this.$emit('queryProId', val.value)
                    }
                    this.mainProductName = val.label;
                    this.initProductDetails(val.value);
                }
            },
            // 查询产品详情
            initProductDetails(val) {
                let param = '';
                param = {
                    id: val,
                    applyNo: this.applyNo
                };
                return new Promise((resolve, reject) => {
                    // let res=queryProductDetail;
                    queryProductDetails(param, "case").then(res => {
                        if (res.code == "0000") {
                            if (res.data) {
                                // // 0是无附加贷，1是有附加贷
                                this.isAdditional = res.data.isAdditional;
                                if (res.data.addProductInfo) {
                                    this.isSubProduct = res.data.addProductInfo.extrasInfo.isProduct;
                                }
                                // 0不贴息 1非灵活贴息 2灵活贴息
                                let _this = this;
                                this.$nextTick(() => {
                                    if (res.data.addProductInfo) {
                                        _this.selectProductInfo = deepClone(res.data.addProductInfo);
                                        _this.additionalDiscountOption = res.data.addProductInfo.discountOption;
                                        _this.addProductId = res.data.addProductInfo.baseInfo.id;
                                        _this.addProductName = res.data.addProductInfo.baseInfo.productName;
                                        _this.addAlgorithmType = res.data.addProductInfo.algorithmType;
                                        _this.addRepaymentData = deepClone(res.data.addProductInfo.repaymentData);

                                        if (res.data.addProductInfo.isTail == "0") {
                                            _this.isAdditionalTail = false;
                                        } else if (res.data.addProductInfo.isTail == "1") {
                                            _this.isAdditionalTail = true;
                                        }

                                    }
                                    if (res.data.mainProductInfo) {
                                        _this.selectCarProductInfo = deepClone(res.data.mainProductInfo);

                                        _this.carDiscountOption = res.data.mainProductInfo.discountOption;
                                        _this.carAlgorithmType = res.data.mainProductInfo.algorithmType;
                                        _this.carRepaymentData = deepClone(res.data.mainProductInfo.repaymentData);

                                        if (res.data.mainProductInfo.isTail == "0") {
                                            _this.isCarTail = false;
                                        } else if (res.data.mainProductInfo.isTail == "1") {
                                            _this.isCarTail = true;
                                        }
                                    }
                                    ;
                                    resolve(res.data);
                                })
                            }
                        }
                    })
                })
            },
            // 融资页面点击保存调接口
            financialSave() {
                let param = this.querySaveData();
                if (!param) {
                    return false;
                }
                if (this.carFinancialId) {
                    updateCostList(param, "case").then(res => {
                        if (res.code == "0000") {
                            this.$Message.success("更新金融产品成功");
                        }
                    })
                } else {
                    saveCostList(param, "case").then(res => {
                        if (res.code == "0000") {
                            res.data.forEach((item, index) => {
                                if (item.costType == "01") {
                                    this.carFinancialId = item.id;
                                } else if (item.costType == "02") {
                                    this.addFinancialId = item.id;
                                }
                            })
                            this.$Message.success("保存金融产品成功");
                        }
                    })
                }
            },
            // 构造保存的贴息入参
            constrDiscountData(discountOption, selectInfo, loanObj, paramObj) {
                // 车贷正常贴息
                if (discountOption == 1) {
                    let subsidyList = [];
                    selectInfo.discountInfo.subsidyList.forEach((item, index) => {
                        let obj = {
                            id: item.id,
                            discountId: item.subsidySide,
                            maxDiscountAmt: item.subsidyMoney,
                            discountScale: item.subsidyRate,
                            totalToTotal: item.totalToTotal,
                            discountParty: item.subsidyName,
                        }
                        subsidyList.push(obj);
                    })
                    paramObj.discountList = subsidyList;
                }
                // 灵活贴息
                if (discountOption == 2) {
                    for (let i = 0; i < loanObj.loadList.length; i++) {
                        if (!loanObj.loadList[i].discountId || !loanObj.loadList[i].discountAmt) {
                            this.$Message.warning("车款贴息列表需填写完整")
                            return false;
                        }
                    }
                    let tempArr = [];
                    for (let i = 0; i < loanObj.loadList.length; i++) {
                        let obj = {};
                        for (let j = 0; j < selectInfo.discountInfo.subsidyList.length; j++) {
                            // 匹配id校验
                            if (loanObj.loadList[i].discountId == selectInfo.discountInfo.subsidyList[j].subsidySide) {
                                if (loanObj.loadList[i].discountAmt > selectInfo.discountInfo.subsidyList[j].subsidyMoney) {
                                    this.$Message.warning("车款贴息额不能大于最大贴息额")
                                    return false;
                                } else {
                                    obj.discountId = loanObj.loadList[i].discountId;
                                    obj.discountAmt = loanObj.loadList[i].discountAmt;
                                    // obj.discountParty=loanObj.loadList[i].discountParty;
                                    obj.id = selectInfo.discountInfo.subsidyList[j].id;
                                    obj.discountScale = selectInfo.discountInfo.subsidyList[j].subsidyRate;
                                    obj.maxDiscountAmt = selectInfo.discountInfo.subsidyList[j].subsidyMoney;
                                    obj.discountParty = selectInfo.discountInfo.subsidyList[j].subsidyName;
                                    obj.totalToTotal = selectInfo.discountInfo.subsidyList[j].totalToTotal;
                                }
                            }
                        }
                        tempArr.push(obj)
                    }
                    paramObj.discountList = tempArr;
                }
                return true;
            },
            // 构造保存的融资列表入参
            constrCapitalData(additionalLoanInfo) {
                let tempItemList = [];
                for (let i = 0; i < additionalLoanInfo.additionalAmtList.length; i++) {
                    let obj = {
                        financeItemCode: additionalLoanInfo.additionalAmtList[i].extrasProjectNo,
                        financeItemName: additionalLoanInfo.additionalAmtList[i].extrasProjectName,
                        financeItemAmt: additionalLoanInfo.additionalAmtList[i].extrasProjectAmt,
                        financeItemTotal: 1,
                        sonList: [],
                    }
                    if (additionalLoanInfo.additionalAmtList[i].itemList.length > 0) {
                        for (let j = 0; j < additionalLoanInfo.additionalAmtList[i].itemList.length; j++) {
                            let childObj = {
                                financeItemCode: additionalLoanInfo.additionalAmtList[i].itemList[j].extrasProjectNo,
                                financeItemName: additionalLoanInfo.additionalAmtList[i].itemList[j].extrasProjectName,
                                financeItemAmt: additionalLoanInfo.additionalAmtList[i].itemList[j].extrasProjectAmt,
                                financeItemTotal: 1,
                            }
                            obj.financeItemTotal = additionalLoanInfo.additionalAmtList[i].itemList.length;
                            obj.sonList.push(childObj)
                        }
                    }
                    tempItemList.push(obj)
                }
                return tempItemList;
            },
            // 点击融资计算
            calculate(btntype) {
                if (!this.valiatePro()) {
                    return false;
                }
                // 车贷信息
                let carLoanInfo = '';
                if (this.isAdditional == '0' || (this.isAdditional == '1' && this.isSubProduct == '1')) {
                    carLoanInfo = this.$refs.carloan.submitCarLoan()
                } else if (this.isAdditional == '1' && this.isSubProduct == '0') {
                    carLoanInfo = this.$refs.carAddLoan.submitCarAddLoan();
                }
                if (!carLoanInfo) {
                    return false;
                }
                let params = {}
                let tempCostList = [];
                let carObj = {
                    costType: "01",
                    discountType: this.carDiscountOption,
                    loanAmt: carLoanInfo.loanAmt,
                    loanTerm: carLoanInfo.loanLimit,
                    custRate: carLoanInfo.custRate,
                    settleRate: carLoanInfo.settleRate,
                    productId: this.mainProductId,
                    algorithmType: this.carAlgorithmType,
                }
                if (this.isAdditional == '1' && this.isSubProduct == '0') {
                    carObj.itemList = this.constrCapitalData(carLoanInfo);
                }

                let totalCarDisAmt = this.constrTotalDiscountAmt(this.carDiscountOption, carLoanInfo, carObj)
                if (!totalCarDisAmt) {
                    return false;
                }
                // 当计算方式为分段时
                if (this.carAlgorithmType == "ballonloan") {
                    carObj.ballonLoanType = this.carRepaymentData.repaymentMethods.finalPaymentCalculationLogic;
                    // 当有尾款
                    if (this.isCarTail) {
                        carObj.tailPayAmt = carLoanInfo.tailPayAmt;
                        carObj.tailPayScale = carLoanInfo.tailPayScale;
                        carObj.isTail = "1";
                    } else {
                        // 当无尾款
                        carObj.isTail = "0";
                        //当等于1时候直接赋值repaymentAmountStages
                        if (this.carRepaymentData.data[0].paymentByStages == "1") {
                            let tempPeroids = '';
                            let tempMoney = '';
                            this.carRepaymentData.data.forEach((item, index) => {
                                let remainAmt = "";
                                if (item.proportionRepaymentSections) {
                                    // 比例先除100
                                    let remainScale = utils.divided(item.proportionRepaymentSections, 100);
                                    // 车款价格乘以比例
                                    remainAmt = Math.round(utils.multiply(carLoanInfo.loanAmt, remainScale) * 100) / 100;
                                } else {
                                    remainAmt = item.repaymentAmountStages;
                                }
                                if (index == this.carRepaymentData.data.length - 1) {
                                    tempPeroids += item.numberInstallments;
                                    tempMoney += remainAmt;
                                } else {
                                    tempPeroids += item.numberInstallments + ',';
                                    tempMoney += remainAmt + ',';
                                }
                            })
                            carObj.peroids = tempPeroids;
                            carObj.money = tempMoney;
                        } else {
                            this.constrPeroidsMoney("car", this.carRepaymentData, carObj, carLoanInfo);
                        }
                    }
                    // 等比累进
                } else if (this.carAlgorithmType == "equalratioret") {
                    carObj.step = this.carRepaymentData.repaymentMethods.numberStepsPerStep;
                    carObj.stepPercent = this.carRepaymentData.repaymentMethods.floatingProportionStepLoan;
                    // 等额累进
                } else if (this.carAlgorithmType == "equalquota") {
                    carObj.step = this.addRepaymentData.repaymentMethods.numberStepsPerStep;
                    // 金额或许不为此后续字段
                    carObj.quota = this.addRepaymentData.floatingProportionStepLoan;
                    // 任意贷计算传等额本息(车贷或者为同一个产品)
                } else if (this.carAlgorithmType == "arbitraryloan") {
                    if (this.modifyRepayList.length > 0) {
                        carObj.algorithmType = this.carAlgorithmType;
                        let rentList = [];
                        this.modifyRepayList.forEach((item, index) => {
                            let obj = {
                                period: item.period,
                                rent: item.rent
                            }
                            rentList.push(obj);
                        })
                        carObj.rentList = rentList;
                    } else {
                        carObj.algorithmType = "equalrental"
                    }
                    // 结构化贷款
                } else if (this.carAlgorithmType == "structuredloan") {
                    carObj.structuredMonth = this.carRepaymentData.repaymentMethods.setAnyNumberCredits;
                    carObj.structuredType = this.carRepaymentData.repaymentMethods.paymentType;
                    carObj.structuredMoney = this.carRepaymentData.repaymentMethods.monthlySupplyAmount;
                }
                tempCostList[0] = carObj;
                // 附加贷
                if (this.isAdditional == "1" && this.isSubProduct == "1") {
                    let additionalLoanInfo = this.$refs.additionalLoan.submitAdditionalLoan();
                    if (!additionalLoanInfo) {
                        return false;
                    }
                    if (additionalLoanInfo.loadAmtList && additionalLoanInfo.loadAmtList.length <= 0) {
                        this.$Message.warning("点击新增填写附加贷数据");
                        return false;
                    }
                    let additionalObj = {
                        costType: "02",
                        discountType: this.additionalDiscountOption,
                        loanAmt: additionalLoanInfo.loanAmt,
                        loanTerm: additionalLoanInfo.loanLimit,
                        custRate: additionalLoanInfo.custRate,
                        settleRate: additionalLoanInfo.settleRate,
                        productId: this.addProductId,
                        algorithmType: this.addAlgorithmType,
                    }
                    //附加贷融资列表
                    additionalObj.itemsList = this.constrCapitalData(additionalLoanInfo);
                    let totalAddDisAmt = this.constrTotalDiscountAmt(this.additionalDiscountOption, additionalLoanInfo, additionalObj)
                    if (!totalAddDisAmt) {
                        return false;
                    }
                    // 当计算方式为分段时
                    if (this.addAlgorithmType == "ballonloan") {
                        additionalObj.ballonLoanType = this.addRepaymentData.repaymentMethods.finalPaymentCalculationLogic;
                        if (additionalLoanInfo.isAdditionalTail) {
                            additionalObj.tailPayAmt = additionalLoanInfo.tailPayAmt;
                            additionalObj.tailPayScale = additionalLoanInfo.tailPayScale;
                            additionalObj.isTail = "1";
                        } else {
                            additionalObj.isTail = "0";
                            //当等于1时候直接赋值repaymentAmountStages
                            if (this.addRepaymentData.data[0].paymentByStages == "1") {
                                let tempPeroids = [];
                                let tempMoney = [];
                                this.addRepaymentData.data.forEach((item, index) => {
                                    let remainAmt = "";
                                    if (item.proportionRepaymentSections) {
                                        // 比例先除100
                                        let remainScale = utils.divided(item.proportionRepaymentSections, 100);
                                        // 车款价格乘以比例
                                        remainAmt = Math.round(utils.multiply(additionalLoanInfo.loanAmt, remainScale) * 100) / 100;
                                    } else {
                                        remainAmt = item.repaymentAmountStages;
                                    }
                                    if (index == this.addRepaymentData.data.length - 1) {
                                        tempPeroids += item.numberInstallments;
                                        tempMoney += item.repaymentAmountStages;
                                    } else {
                                        tempPeroids += item.numberInstallments + ',';
                                        tempMoney += item.repaymentAmountStages + ',';
                                    }
                                })
                                additionalObj.peroids = tempPeroids;
                                additionalObj.money = tempMoney;
                            } else {
                                this.constrPeroidsMoney('add', this.addRepaymentData, additionalObj, additionalLoanInfo)
                            }
                        }
                        // 等比累进
                    } else if (this.addAlgorithmType == "equalratioret") {
                        additionalObj.step = this.addRepaymentData.repaymentMethods.numberStepsPerStep;
                        additionalObj.stepPercent = this.addRepaymentData.floatingProportionStepLoan;
                        // 等额累进
                    } else if (this.addAlgorithmType == "equalquota") {
                        additionalObj.step = this.addRepaymentData.repaymentMethods.numberStepsPerStep;
                        // 金额或许不为后续字段
                        additionalObj.quota = this.addRepaymentData.floatingProportionStepLoan;
                        // 结构化贷款
                    } else if (this.carAlgorithmType == "structuredloan") {
                        additionalObj.structuredMonth = this.addRepaymentData.repaymentMethods.setAnyNumberCredits;
                        additionalObj.structuredType = this.addRepaymentData.repaymentMethods.paymentType;
                        additionalObj.structuredMoney = this.addRepaymentData.repaymentMethods.monthlySupplyAmount;
                    }
                    tempCostList[1] = additionalObj;
                }
                params.costList = tempCostList;
                financeCalculation(params, "case").then(res => {
                    if (res.code == "0000") {
                        if (btntype == "calculate") {
                            this.$emit('isShowModel', true)
                            if (this.carAlgorithmType == "arbitraryloan") {
                                this.$emit('showCalculate', true, false)
                            }
                        }
                        this.showPayMoney(res.data, btntype);
                    }
                }).then(re=>{
                    if (btntype == "update") {
                        this.financialSave();
                    }
                })
            },
            // 构造计算的灵活贴息总额
            constrTotalDiscountAmt(discountOption, loanObj, paramObj) {
                if (discountOption == 2) {
                    let totalAmt = 0;
                    for (let i = 0; i < loanObj.loadList.length; i++) {
                        if (!loanObj.loadList[i].discountId || !loanObj.loadList[i].discountAmt) {
                            this.$Message.warning("贴息列表需查询完整")
                            return false;
                        } else {
                            totalAmt += parseFloat(loanObj.loadList[i].discountAmt)
                        }
                    }
                    paramObj.discountAmt = totalAmt;
                }
                return true;
            },
            // 构造peroids，money数据
            constrPeroidsMoney(type, repaymentData, obj, loanInfo) {
                let loanAmt = "";
                let tempPeroids = '';
                let tempMoney = '';

                // 车贷或车和附加贷合并
                if (type == "car") {
                    if (repaymentData.repaymentMethods.finalPaymentBenchmark == "1") { //总融资额((车贷+附加贷)-首付金额)*比例
                        loanAmt = loanInfo.loanAmt;
                    } else if (repaymentData.repaymentMethods.finalPaymentBenchmark == "0") { //车价金额* 比例
                        loanAmt = loanInfo.carPrice;
                    } else if (repaymentData.repaymentMethods.finalPaymentBenchmark == "2") { //合同价格*比例
                        // 有附加贷同一个产品
                        if (this.isAdditional == "1" && this.isSubProduct == '0') {
                            loanAmt = utils.add(loanInfo.carPrice, loanInfo.additionalTotalAmt);
                            // 有附加贷不是同一个产品或无附加贷
                        } else {
                            loanAmt = loanInfo.carPrice;
                        }
                    } else if (repaymentData.repaymentMethods.finalPaymentBenchmark == "3") {//车辆融资额(车贷-首付比例)*比例
                        let scale = utils.sub(100, loanInfo.downPayScale);
                        let scalePrecent = utils.divided(scale, 100);
                        loanAmt = utils.multiply(loanInfo.carPrice, scalePrecent)
                    }
                    // 附加贷
                } else if (type == "add") {
                    if (repaymentData.repaymentMethods.finalPaymentBenchmark == "1") { //总融资额((车贷+附加贷)-首付金额)*比例
                        loanAmt = loanInfo.loadAmtList[0].loanAmt;
                    } else if (repaymentData.repaymentMethods.finalPaymentBenchmark == "0") { //车价金额* 比例
                        loanAmt = loanInfo.additionalTotalAmt;
                    } else if (repaymentData.repaymentMethods.finalPaymentBenchmark == "2") {//合同价格*比例
                        // 有附加贷且不为同一个产品
                        loanAmt = loanInfo.additionalTotalAmt;
                    } else if (repaymentData.repaymentMethods.finalPaymentBenchmark == "3") {//车辆融资额(车贷-首付比例)*比例
                        let scale = utils.sub(100, loanInfo.downPayScale);
                        let scalePrecent = utils.divided(scale, 100);
                        loanAmt = utils.multiply(loanInfo.additionalTotalAmt, scalePrecent)
                    }
                }
                repaymentData.data.forEach((item, index) => {
                    let remainAmt = "";
                    if (item.proportionRepaymentSections) {
                        // 比例先除100
                        let remainScale = utils.divided(item.proportionRepaymentSections, 100);
                        // 车款价格乘以比例
                        remainAmt = Math.round(utils.multiply(loanAmt, remainScale) * 100) / 100;
                    } else {
                        remainAmt = item.repaymentAmountStages;
                    }
                    if (index == repaymentData.data.length - 1) {
                        tempPeroids += item.numberInstallments;
                        tempMoney += remainAmt;
                    } else {
                        tempPeroids += item.numberInstallments + ',';
                        tempMoney += remainAmt + ',';
                    }
                })
                obj.peroids = tempPeroids;
                obj.money = tempMoney;
            },
            // 回显还款计划表
            showPayMoney(data, btntype) {
                // 还款计划表按钮跟更新按钮公用部分
                data.costList.forEach((item, index) => {
                    if (item.costType == "02") {
                        this.addMonthPay = item.firstRent;
                        this.addTotalRent = item.totalRent;
                        this.addTotalInterest = item.totalInterest;
                        // 附加贷的贴息金额
                        this.addDiscount = item.discountAmt;
                    }
                    if (item.costType == "01") {
                        this.carMonthPay = item.firstRent;
                        this.carTotalRent = item.totalRent;
                        this.carTotalInterest = item.totalInterest;

                        // 车贷的贴息金额
                        this.carDiscount = item.discountAmt;
                    }
                })
                // 回显合计信息
                this.totalInfoData.totalInterest = data.totalInterest;//利息总额
                this.totalInfoData.totalRent =utils.add(this.addMonthPay,this.carMonthPay);//首期月供总额
                this.totalInfoData.totalRentOld =utils.add(this.addMonthPay,this.carMonthPay);//首期月供总额
                if (btntype == "calculate") {
                    let titleList = [];
                    this.$emit('caluMaxValue', data.maxRent);
                    if (data.repaymentList.length > 0) {
                        this.tempRepaymentList = deepClone(data.repaymentList);
                    }
                    this.proessForm.proessList = this.queryProessList(data.repaymentList)
                    if (data.rentList && data.rentList.length > 0) {
                        this.modifyRepayList = data.rentList;
                    } else {
                        this.modifyRepayList = [];
                    }
                    let costType = [];
                    // 回显月供
                    data.costList.forEach((item, index) => {
                        costType.push(item.costType);
                        if (item.costType == "02") {
                            this.additionalProessForm.proessList = this.queryProessList(item.repaymentList)
                        }
                        if (item.costType == "01") {
                            this.carProessForm.proessList = this.queryProessList(item.repaymentList)
                        }
                    })
                    // 无附加贷返回
                    if (costType.indexOf('02') == "-1") {
                        let titleList = [{value: "00", title: "还款计划表"}];
                        this.$emit('scheduleTitle', titleList)
                    } else {
                        let titleList = [{value: "00", title: "还款计划表"}, {value: "01", title: "车款还款计划表"}, {
                            value: "02",
                            title: "附加贷还款计划表"
                        }];
                        this.$emit('scheduleTitle', titleList)
                    }
                    this.$emit('passValiate')
                }
              /*  else if (btntype == "update") {
                    this.financialSave();
                }*/

            },
            // 获取车款，附加贷，总的还款计划表
            queryProessList(repaymentList) {
                let tempArr = [];
                if (repaymentList && repaymentList.length > 0) {
                    repaymentList.forEach((item, index) => {
                        let obj = {
                            no: item.no,
                            inputValue: item.yueGong.toString(),
                            proessValue: [],
                            benJin: item.benJin,
                            compoundInterest: item.compoundInterest,
                            liXi: item.liXi,
                            monthlyInterest: item.monthlyInterest,
                            yuE: item.yuE,
                            yueGong: item.yueGong,
                            modifyAmount: 0
                        }
                        obj.proessValue[0] = 0;
                        obj.proessValue[1] = item.yueGong;
                        tempArr.push(obj);
                    })
                }
                return tempArr;
            },
            // 还款计划表计算
            calculateIntrate(btntype) {
                // 对比当前修改的期数与金额
                let tempArr = [];
                this.proessForm.proessList.forEach((itemProess, indexProess) => {
                    this.tempRepaymentList.forEach((item, index) => {
                        if (itemProess.no == item.no) {
                            if (itemProess.inputValue != item.yueGong) {
                                let obj = {
                                    period: itemProess.no,
                                    rent: itemProess.inputValue
                                }
                                tempArr.push(obj);
                            }
                        }
                    })
                })
                if (tempArr.length > 0) {
                    if (this.modifyRepayList.length > 0) {
                        let tempArrPeriod = [];
                        tempArr.forEach((item, index) => {
                            tempArrPeriod.push(item.period);
                        })
                        //  判断上次修改的期数值modifyRepayList是否在这次修改期数tempArr中，不在的话push到tempArr,在的话不做任何处理
                        this.modifyRepayList.forEach((itemRepay, index) => {
                            if (tempArrPeriod.indexOf(itemRepay.period) == "-1") {
                                let obj = {
                                    period: itemRepay.period,
                                    rent: itemRepay.rent
                                }
                                tempArr.push(obj);
                            }
                        })
                    }
                    // 车贷信息
                    let carLoanInfo = "";
                    if (this.isAdditional == '0' || (this.isAdditional == '1' && this.isSubProduct == '1')) {
                        carLoanInfo = this.$refs.carloan.submitCarLoan()
                    } else if (this.isAdditional == '1' && this.isSubProduct == '0') {
                        carLoanInfo = this.$refs.carAddLoan.submitCarAddLoan();
                    }
                    if (!carLoanInfo) {
                        return false;
                    }
                    let queryFormEl = this.queryFormEl();
                    queryFormEl.validate((valid) => {
                        if (valid) {
                            // 车贷贴息相关信息
                            let params = {
                                costType: "01",
                                loanAmt: carLoanInfo.loanAmt,
                                loanTerm: carLoanInfo.loanLimit,
                                custRate: carLoanInfo.custRate,
                                settleRate: carLoanInfo.settleRate,
                                algorithmType: this.carAlgorithmType,
                                productId: this.mainProductId
                            }
                            params.applyNo = this.applyNo;
                            params.rentList = tempArr;
                            getArbitraryRepaymentPlan(params).then(res => {
                                if (res.code == "0000") {
                                    this.showPayMoney(res.data, btntype)
                                }
                            })
                        }
                    })
                } else {
                    // this.$Message.warning("请修改租金后重新计算")
                }
            },
            valiatePro() {
                let proVailate = false;
                this.$refs.financialProdForm.validate((valid) => {
                    if (valid) {
                        proVailate = valid;
                    } else {
                        proVailate = false;
                    }
                })
                return proVailate;
            },
            valiateCarLoan() {
                return this.$refs.carloan.submitCarLoan()
            },
            valiateCarAddLoan() {
                return this.$refs.carAddLoan.submitCarAddLoan();
            },
            valiateAdditionalLoan() {
                return this.$refs.additionalLoan.submitAdditionalLoan()
            },
            queryTotalLoanAmt() {
                let submitTotalInfo = this.$refs.totalInfo.submitTotalInfo();
                return submitTotalInfo.totalLoanAmt;
            },
            querySaveData() {
                // 保存获取合计信息
                let submitTotalInfo = this.$refs.totalInfo.submitTotalInfo();
                // 无附加贷或有附加贷不是一个产品
                let carLoanInfo = "";
                let totalArr = [];
                let carObj = {
                    costType: "01",
                    discountType: this.carDiscountOption,
                    productId: this.mainProductId,
                    productName: this.mainProductName,
                    discountAmt: this.carDiscount,
                    totalRent: this.carTotalRent,
                    totalInterest: this.carTotalInterest,
                    algorithmType: this.carAlgorithmType,
                }
                if (this.isAdditional == '0' || (this.isAdditional == '1' && this.isSubProduct == '1')) {
                    carLoanInfo = this.$refs.carloan.submitCarLoan();
                    if (this.isAdditional == '1' && this.isSubProduct == '1') {
                        carObj.isSubProduct = this.isSubProduct;
                    }
                } else if (this.isAdditional == '1' && this.isSubProduct == '0') {
                    carLoanInfo = this.$refs.carAddLoan.submitCarAddLoan();
                    carObj.addAmt = carLoanInfo.additionalTotalAmt;
                    carObj.itemsList = this.constrCapitalData(carLoanInfo);
                    carObj.isSubProduct = this.isSubProduct;
                }
                carObj.contractAmt = carLoanInfo.carPrice;
                carObj.loanTerm = carLoanInfo.loanLimit;
                carObj.downPayScale = carLoanInfo.downPayScale;
                carObj.downPayAmt = carLoanInfo.downPayAmt;
                carObj.loanAmt = carLoanInfo.loanAmt;
                carObj.settleRate = carLoanInfo.settleRate;
                carObj.custRate = carLoanInfo.custRate;
                carObj.monthPayAmt = carLoanInfo.monthPayAmt

                // 更新时候用的车贷id
                if (this.carFinancialId) {
                    carObj.id = this.carFinancialId;
                }
                // 有尾款
                if (this.isCarTail) {
                    carObj.tailPayAmt = carLoanInfo.tailPayAmt;
                    carObj.tailPayScale = carLoanInfo.tailPayScale;
                    carObj.isTail = "1";
                } else {
                    // 无尾款
                    carObj.isTail = "0";
                }
                let carDiscountResult = this.constrDiscountData(this.carDiscountOption, this.selectCarProductInfo, carLoanInfo, carObj);
                // 如果贴息校验不通过
                if (!carDiscountResult) {
                    return false;
                }
                totalArr[0] = carObj;
                // 有附加贷不是同一个产品
                if (this.isAdditional == '1' && this.isSubProduct == '1') {
                    // 保存获取附加贷信息
                    let additionalLoanInfo = this.$refs.additionalLoan.submitAdditionalLoan();
                    let additionalObj = {
                        costType: "02",
                        discountType: this.additionalDiscountOption,
                        productId: this.addProductId,
                        isSubProduct: this.isSubProduct,
                        productName: this.addProductName,
                        contractAmt: additionalLoanInfo.additionalTotalAmt,
                        loanTerm: additionalLoanInfo.loanLimit,
                        downPayScale: additionalLoanInfo.downPayScale,
                        downPayAmt: additionalLoanInfo.downPayAmt,
                        loanAmt: additionalLoanInfo.loanAmt,
                        discountAmt: this.addDiscount,
                        settleRate: additionalLoanInfo.settleRate,
                        custRate: additionalLoanInfo.custRate,
                        monthPayAmt: additionalLoanInfo.monthPayAmt,
                        totalRent: this.addTotalRent,
                        totalInterest: this.addTotalInterest,
                        algorithmType: this.addAlgorithmType,
                    }
                    // 更新时候用的附加贷id
                    if (this.addFinancialId) {
                        additionalObj.id = this.addFinancialId;
                    }
                    if (additionalLoanInfo.isAdditionalTail) {
                        additionalObj.tailPayAmt = additionalLoanInfo.tailPayAmt;
                        additionalObj.tailPayScale = additionalLoanInfo.tailPayScale;
                        additionalObj.isTail = "1";
                    } else {
                        additionalObj.isTail = "0";
                    }
                    let addDiscountResult = this.constrDiscountData(this.additionalDiscountOption, this.selectProductInfo, additionalLoanInfo, additionalObj);
                    // 如果贴息校验不通过
                    if (!addDiscountResult) {
                        return false;
                    }
                    //附加贷融资列表
                    additionalObj.itemsList = this.constrCapitalData(additionalLoanInfo);
                    totalArr[1] = additionalObj;
                }
                let param = {
                    applyNo: this.applyNo,
                    costList: totalArr,
                    totalContractAmt: submitTotalInfo.totalcontAmt,
                    totalLoanAmt: submitTotalInfo.totalLoanAmt,
                    totalFirstAmt: submitTotalInfo.totalFirstAmt,
                    totalDiscountAmt: submitTotalInfo.totalDiscountAmt,
                    totalInterest: submitTotalInfo.totalInterest,
                    totalRent: submitTotalInfo.totalRent,
                }
                return param;
            },
            getTheoryloanAmt(theoryloanAmt){
                this.$refs.totalInfo.setTotalLoanAmt(theoryloanAmt)
            }
        }
    }

</script>
<style scoped>
    .prodName >>> .ivu-select-placeholder {
        color: #515a6e;
    }

    .prodName >>> .ivu-select-selection {
        width: 500px;
    }
</style>
